package com.qrxl.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.qrxl.common.JGConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "operator", String.class, getOperator());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        this.strictUpdateFill(metaObject, "operator", String.class, getOperator());
    }

    //获取操作人
    private String getOperator() {
        String defaultOperator = "nobody";
        if (RequestContextHolder.getRequestAttributes() == null) {
            return defaultOperator;
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object userLoginInfo = request.getSession().getAttribute(JGConstant.USER_SESSION_KEY);

        if (userLoginInfo == null) {
            return defaultOperator;
        }
        // todo return ((UserLoginInfo) userLoginInfo).getLoginName();
        return null;
    }

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor pageination = new PaginationInterceptor();
        pageination.setLimit(100000);
        return pageination;
    }
}
